import { t } from 'i18next'
import React, { useState, useEffect, useRef } from 'react'
import { Modal, Message, InnerInputRef } from '@kedacom/react-next'
import { revert_vmp, SelectItem, Vmp } from '../interface'
import { transVmpDTO } from '../translator'
import { Alert, confirmModal } from '@/components/Alert'
import { useRequest } from 'ahooks'
import { store as mccStore } from '../../../store'
import {
	fetchGetVmpPlanList,
	fetchGetVmpPlan,
	fetchSaveVmpPlan,
	fetchEditVmpPlan,
	fetchDeleteVmpPlan,
} from '@/api/manager/vmp'

import { vmpStyleData } from '../VmpView/interface'
import { useVmpTypeStore } from '../store.get'
export default function useService({ getVmpParam }: { getVmpParam: () => Vmp | null }) {
	const meetingMoid = mccStore.getState().mccInfo.meetingMoid
	const useStore = useVmpTypeStore((state) => state.getStore())
	const { data, updateData } = useStore((state) => ({
		data: state.data,
		updateData: state.updateData,
	}))
	const inputRef = useRef<InnerInputRef>(null)
	const [planValue, setPlanValue] = useState('0') //预案id
	const [planOptions, setPlanOptions] = useState<SelectItem[]>([
		{ label: t('默认预案'), value: '0', mode: undefined, layout: undefined, count: t('默认预案') },
	]) //预案选项
	const [beSelectPlanOptionsItem, setBeSelectPlanOptionsItem] = useState<SelectItem>({
		label: t('默认预案'),
		value: '0',
		mode: undefined,
		layout: undefined,
		count: t('默认预案'),
	})
	const [name, setName] = useState('') //预案名称
	const [isSavePlanOpen, setIsSavePlanOpen] = useState(false) //预案名称弹窗
	const { data: vmpPlanData, run } = useRequest(() => fetchGetVmpPlanList(meetingMoid))
	useEffect(() => {
		if (vmpPlanData && vmpPlanData.success) {
			let arr: SelectItem[] = vmpPlanData.data
				? vmpPlanData.data.map((item) => {
						let _name = ''
						_name += item.name
						return {
							label: item.name,
							value: item.id,
							mode: item.mode,
							layout: item.layout,
							count: _name,
						}
				  })
				: []
			arr.unshift({
				label: t('默认预案'),
				value: '0',
				mode: undefined,
				layout: undefined,
				count: t('默认预案'),
			})
			setPlanOptions(arr)
		}
	}, [vmpPlanData])
	useEffect(() => {
		// console.log(data.mt_name_style, planOptions)
		let _item = planOptions.find((item) => item.label === data.name)
		_item && setBeSelectPlanOptionsItem(_item)
		setPlanValue(_item?.value ?? '0')
	}, [data.name, planOptions])
	//载入预案
	const changePlan = async (id: string) => {
		if (id === '0') {
			updateData(null)
			return
		}
		fetchGetVmpPlan(meetingMoid, id).then((res) => {
			if (res.success) {
				setPlanValue(id)
				let _data = new Vmp(res)
				updateData(_data)
				Message.info(t('预案载入成功'))
			} else {
				Alert(t('获取画面合成预案失败'))
			}
		})
	}
	//删除预案
	const deletePlan = (e: React.MouseEvent, item: SelectItem) => {
		e.stopPropagation()
		confirmModal({
			msg: <div>{t('是否确定删除{{name}}？', { name: item.label })}</div>,
			onOk: async () => {
				fetchDeleteVmpPlan(meetingMoid, item.value).then((res) => {
					if (res.success) {
						let arr = planOptions.filter((i) => i.value !== item.value)
						setPlanOptions(arr)
						if (planValue === item.value) {
							setPlanValue('0')
							updateData(null)
						}
					} else {
						Alert(res.description ?? t('删除预案失败'))
					}
				})
			},
		})
	}
	//保存预案
	const savePlanClick = () => {
		if (planValue === '0') {
			setIsSavePlanOpen(true)
			setName('')
		} else {
			let param = getVmpParam()
			if (!param) return
			/**终端画面合成只在端口会议存在端口会议广播始终开启由于这边预案和画面合成用的是同一个*/
			if (useVmpTypeStore.getState().type !== 'vmp') {
				param = { ...param, broadcast: 1 }
			}
			fetchEditVmpPlan(meetingMoid, planValue, transVmpDTO(revert_vmp(param), 'plan')).then((res) => {
				if (res.success) {
					Message.info(t('已覆盖保存预案'))
					run()
				} else {
					Alert(res.description ?? t('覆盖保存预案失败'))
				}
			})
		}
	}
	const saveAsPlan = () => {
		setIsSavePlanOpen(true)
		setName(data.name + '1')
	}
	const savePlan = async () => {
		let valid = await inputRef.current?.valid()
		if (!valid) return
		let param = getVmpParam()
		if (!param) return
		let newParam = { ...param, name, id: '' }
		/**终端画面合成只在端口会议存在端口会议广播始终开启由于这边预案和画面合成用的是同一个*/
		if (useVmpTypeStore.getState().type !== 'vmp') {
			newParam = { ...newParam, broadcast: 1 }
		}
		fetchSaveVmpPlan(meetingMoid, transVmpDTO(revert_vmp(newParam), 'plan')).then((res) => {
			if (res.success) {
				Message.info(t('预案保存成功'))
				updateData(newParam)
				setIsSavePlanOpen(false)
				run()
			} else {
				Alert(res.description ?? t('预案保存失败'))
			}
		})
	}
	const change = (item: SelectItem) => {
		if (item.value == '0') {
			return 'default'
		} else if (item.mode == 2) {
			return 'auto'
		} else {
			const _item = vmpStyleData.find((_vmpStyleItem) => _vmpStyleItem.id === item.layout)
			return _item?.className
		}
	}
	return {
		/** 预案选项 */
		planOptions,
		/** 预案选项值 */
		planValue,
		/** 载入预案 */
		changePlan,
		/** 删除预案 */
		deletePlan,
		/** 保存预案弹窗是否打开 */
		isSavePlanOpen,
		/** 保存预案弹窗是否打开方法 */
		setIsSavePlanOpen,
		/** 保存或修改预案 */
		savePlanClick,
		/** 保存新预案 */
		savePlan,
		/** 预案名 */
		name,
		/** 设置预案名 */
		setName,
		/**被选中预案 */
		beSelectPlanOptionsItem,
		/**预案另存为 */
		saveAsPlan,
		change,
		inputRef,
	}
}
